import axios, {
    AxiosError,
} from "axios";
import { useJackpotStore } from "@/store";
import Eventbus from "@/utils/EventBus";


export class HttpRequest {
    private baseUrl: string = import.meta.env.VITE_BASE_URL;
    private timeout: number = 10000;
    private axiosInstance: any = null;

    constructor() {
        this.init();
    }

    init() {

        this.axiosInstance = axios.create({
            baseURL: this.baseUrl,
            timeout: this.timeout,
        });
        // 请求拦截器
        this.axiosInstance.interceptors.request.use(
            (config: any) => {
                const token = useJackpotStore().$state.token ?? "";
                config.headers["Authorization"] = token ? "Bearer " + token : "";
                return config;
            },
            (error: AxiosError) => {
                return Promise.reject(error);
            }
        );
        // 响应拦截器
        this.axiosInstance.interceptors.response.use(
            (response: any) => {
                if (response.config.responseType === 'blob') {
                    return response;
                }

                if (response.data.code >= 400) {
                    Eventbus.emit('error-message', response.data.message);
                    if (response.data.code === 401) {
                        setTimeout(() => { window.location.reload(); }, 1000);
                    }
                }
                return response.data;
            },
            (error: any) => {
                Eventbus.emit('error-message', error.response && error.response.data && (error.response.data.message || error.response.data.msg) || '请求失败');
                if (error.response.data && error.response.data.code == 401) {
                    setTimeout(() => { window.location.reload(); }, 1000);
                }
                return Promise.reject(error);
            }
        );
    }
    public postFile(url: string, data?: any, config?: any) {
        return axios.post(this.baseUrl + url, data, {
            ...config,
        });
    }

    // get
    public get(url: string, params?: any) {
        return this.axiosInstance.get(url, { params });
    }

    // post
    public post(url: string, data?: any) {
        return this.axiosInstance.post(url, data);
    }

    // patch
    public patch(url: string, data?: any) {
        return this.axiosInstance.patch(url, data);
    }

    // put
    public put(url: string, data?: any) {
        return this.axiosInstance.put(url, data);
    }

    // delete
    public delete(url: string, params?: any) {
        return this.axiosInstance.delete(url, { params });
    }
}

export default new HttpRequest();